package com.keter.framework.persist.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.keter.framework.persist.util.ValidateUtil;
import com.jfinal.plugin.activerecord.Model;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

public  abstract class BaseModel<M extends BaseModel> extends Model<M> {
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(BaseModel.class);
   
    public void setID(){
    	this.set("id", UUID.randomUUID());
    }

    public BaseModel<M> parse(String json){
        Map map  = (Map) JSONObject.parse(json);
        this._setAttrs(map);
        return this;
    }

    public BaseModel<M> parse(JSONObject json){
        Map map  = (Map) JSONObject.parse(json.toJSONString());
        this._setAttrs(map);
        return this;
    }

	/**
	 * <p>Method ：getNum
	 * <p>Description : 返回主键
	 * @return
	 * @version 1.0.0
	 */
	public Object getID() {
		return get("id");
	}
	
	public Object getID(String attr) {
//		return String.valueOf(getNum(attr));
		return get(attr);
	}
	
	public Integer getNum(String attr) {
	    if(super._getAttrs().get(attr) instanceof Integer){
	        return this.getInt(attr);
	    }
	    if(super._getAttrs().get(attr) instanceof Long){
	        return this.getLong(attr).intValue();
	    }
	    throw new NullPointerException("不支持的主键类型！");
	}
    
    /**
     * <p>Method ：wrap
     * <p>Description : 将入参包装成对象数组
     * @param objects
     * @return 
     * @version 1.0.0
     */
    protected  Object[] wrap(Object... objects) {
    	return objects;
	}
    
    /**
     * <p>Method ：validate
     * <p>Description : 后台校验(子类强制实现)
     *<br>对于前台已经添加了js校验的应用，通常后台数据校验失败并非普通请求而是源于非法攻击
     *<br>因此只需要简单记录，不需要感知和特别处理
     *<p>期望使用 ValidateUtil 进行校验，自动实现失败时只抛出运行时异常并简单记录错误信息
     * @see ValidateUtil
     * @return 
     */
    abstract protected void validate();
    
    /**
     * Model专属校验工具
     * @return 
     * @date    2015年11月2日
     */
    protected ValidateUtil validator(){
        return new ValidateUtil(this);
    }

    @Override
    public boolean save(){
        validate();
        return super.save();
    }

    @Override
    public boolean update(){
    	validate();
    	return super.update();
    }

    private static Map<String, Object> json2Map(String json) {
        try {
            json = URLDecoder.decode(json, "utf-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("json转换异常", e);
        }
        return (Map<String, Object>) JSON.parse(json);
    }


    protected static String extractCommaStrToSqlIn(final String CommaStr) {
        AtomicReference<String> sqlIn = new AtomicReference<>("");
        Arrays.stream(CommaStr.split(",")).forEach(s -> {
            sqlIn.set(sqlIn.get()+"'" + s + "',");});
        return StringUtils.substringBeforeLast(sqlIn.get(),",");
    }

    public static void main(String[] args) {
        System.out.println(extractCommaStrToSqlIn("1,2,3"));
    }

}